package com.dts.backproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dts.backproject.entity.po.User;
import com.dts.backproject.exception.MyException;
import com.dts.backproject.mapper.UserMapper;
import com.dts.backproject.service.UserService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        if (user == null) {
            throw new MyException("用户名或密码错误！");
        }
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getEmail, user.getEmail()).eq(User::getPassword, user.getPassword());

        return userMapper.selectOne(eq);
    }

    public void register(User user) {
        int insert = 0;
        if (user != null) {
            insert = userMapper.insert(user);
        }

        if (insert == 0){
            throw new MyException("注册失败");
        }
    }

    @Override
    public User findByEmail(String email) {
        if(StringUtils.isEmpty(email)){
            throw new MyException("查询用户失败");
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, email));
        return user;
    }

    @Override
    public void saveUser(User user) {
        if(user.getEmail() == null){
            throw new MyException("新增用户失败");
        }

        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
        User currentUser = userMapper.selectById(user.getId());
        if(currentUser == null){
            throw new MyException("暂无该用户!");
        }
        if(user.getEmail() == null){
            throw new MyException("用户信息更新失败");
        }
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(String email) {
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getEmail, email);
        userMapper.delete(eq);
    }

    @Override
    public void profile(User user) {
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getEmail, user.getEmail());
        User currentUser = userMapper.selectOne(eq);
        if(currentUser == null){
            throw new MyException("用户查询失败！");
        }

        user.setId(currentUser.getId());
        int i = userMapper.updateById(user);
        if(i == 0){
            throw new MyException("用户信息更新成功！");
        }
    }
}
